package site.edody.dframe.ssoserver.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.model.Group;
import org.ssssssss.magicapi.core.model.TreeNode;
import org.ssssssss.magicapi.core.service.MagicResourceService;

import java.io.InputStream;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Order(1)
@Component
public class SsoApiScriptConfig  implements ApplicationRunner {

    private final Logger log = LoggerFactory.getLogger(SsoApiScriptConfig.class);
    private static final String DFRAME = "dframe";
    private static final String SCRIPTRESOURCE = "ssoscript.zip";
    @Autowired
    MagicResourceService service;

    @Override
    public void run(ApplicationArguments args) throws Exception {


        if (service.tree() == null || service.tree().get("api") == null || service.tree().get("api").getChildren() == null ||  service.tree().get("api").getChildren().size() <=0){
            log.info("Sso Server 未有接口，将进行初始化导入.......");
            initScript(true);
        } else {
            log.info("系统已经存在接口数据，将进行局部更新.... ");
            List<TreeNode<Group>> dframenode = getNodesByName(service.tree().get("api").getChildren(),DFRAME);
            if ( dframenode != null){ // 存在，则已有，不需要操作
                log.info("系统已经存在dframe节点接口数据，不需要再做操作");
            } else {
                log.info("已经存在接口数据，不包括dframe，将进行初始化更新...");
                initScript(true);
            }
        }

    }

    private void initScript(boolean isfull) throws Exception {
        // 初始化操作

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(SCRIPTRESOURCE);
        boolean upload = service.upload(inputStream, isfull);
        if (!upload){
            throw new Exception("加载初始脚本异常");
        }
    }


    /**
     * 根据节点名称获取资源
     * @param nodes
     * @param nodename
     * @return
     */
    private List<TreeNode<Group>> getNodesByName(List<TreeNode<Group>> nodes, String nodename){
        AtomicReference<List<TreeNode<Group>>> rs = new AtomicReference<>();
        nodes.iterator().forEachRemaining((node) -> {
            if (nodename.equals(node.getNode().getName())){
                rs.set(node.getChildren());
            }
        });
        return rs.get();
    }

}